// 添加后台请求端点配置
const apiConfig = {
    queryProducts: '/products/api/user-products/',
    productTypes: '/products/api/product-types/',
    users: '/accounts/user_list/',
    createProduct: '/products/api/create-product/'
};

// 初始化分页
let currentPage = 1;

// 跳转仪表盘
function loadProductDetail(productId) {
    window.location.href = `/products/api/dashboard/${productId}/`;  // 跳转前端路由
}



// 渲染产品卡片
function renderProducts(products) {
    const container = $('#products-container');
    const addTemplate = $('#add-card-template').html();

    container.empty();

    // 空状态处理
    if (!products.length) {
        container.html(`
            <div class="col-12 d-flex justify-content-center">
                <div class="card add-card">
                    <div class="card-body d-flex flex-column justify-content-center align-items-center">
                        <button class="btn btn-link text-reset">
                            <i class="fas fa-plus-circle fa-3x text-muted"></i>
                        </button>
                        <span class="text-muted mt-2">点击创建第一个产品</span>
                    </div>
                </div>
            </div>
        `);
        return;
    }

    // 生成所有产品卡片
    products.forEach(product => {
        const card = $(`
            <div class="col">
                <div class="card product-card h-100">
                    <img src="/${product.logo}" 
                         class="product-logo card-img-top" 
                         alt="产品logo">
                         
                    <div class="card-body">
                        <h5 class="card-title">${product.name}</h5>
                        <p class="card-text">${truncateDescription(product.description)}</p>
                        <small class="text-muted mt-auto">创建时间：${formatDate(product.create_time)}</small>
                    </div>
                </div>
            </div>
        `);

        // 添加点击事件（匹配图片中的蓝色高亮逻辑）
        card.find('.product-card').on('click', function () {
            $('.product-card').removeClass('active-card'); // 移除其他卡片激活状态
            $(this).addClass('active-card'); // 当前卡片激活
            loadProductDetail(product.id);
            updateSelector(product.id, product.name);
        });
        container.append(card);
    });

    // 添加补充卡片
    container.append(addTemplate);
}


function updateSelector(productId, productName) {
    const $selector = $('.product-selector');

    // 更新按钮显示（匹配图片中的深蓝色文字）
    $selector.find('button')
        .text(productName)
        .removeClass('text-muted')
        .css('color', '#2A3950');

    // 同步下拉菜单选中状态（匹配图片中的蓝色高亮）
    $selector.find('.dropdown-item').removeClass('active');
    $selector.find(`[data-product-id="${productId}"]`).addClass('active');
}




// 分页控制
function updatePagination(response) {
    const pagination = $('#pagination');
    pagination.empty();

    if (response.total_pages <= 1) {
        pagination.hide();
        return;
    }
    pagination.show();

    // 当前页范围控制（重要修复）
    const startPage = Math.max(1, Math.min(
        currentPage - 1,
        response.total_pages - 2
    ));
    const endPage = Math.min(response.total_pages, startPage + 2);

    // 上一页按钮
    pagination.append(`
        <li class="page-item ${!response.has_previous ? 'disabled' : ''}">
            <a class="page-link page-arrow" href="#" data-page="${currentPage - 1}">
                &laquo;
            </a>
        </li>
    `);

    // 页码按钮（严格按实际页数生成）
    for (let i = 1; i <= response.total_pages; i++) {
        if (i < startPage || i > endPage) continue; // 范围过滤
        pagination.append(`
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link page-number" href="#" data-page="${i}">
                    ${i}
                </a>
            </li>
        `);
    }

    // 下一页按钮
    pagination.append(`
        <li class="page-item ${!response.has_next ? 'disabled' : ''}">
            <a class="page-link page-arrow" href="#" data-page="${currentPage + 1}">
                &raquo;
            </a>
        </li>
    `);
}

// 辅助函数
function truncateDescription(text, maxLength = 100) {
    return text.length > maxLength ? text.substring(0, maxLength - 3) + '...' : text;
}

function formatDate(timestamp) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

// 加载产品数据
function loadProducts(page = 1) {
    $.ajax({
        url: `${apiConfig.queryProducts}?page=${page}`,
        success: (response) => {
            currentPage = response.current_page;
            renderProducts(response.products);
            updatePagination(response);
        },
        error: (xhr) => {
            console.error('加载失败:', xhr.statusText);
        }
    });
}

// 事件绑定
$(document).ready(() => loadProducts()).on('click', '.page-link', function (e) {
        e.preventDefault();
        loadProducts($(this).data('page'));
    });


// 弹窗控制
function initAddProductModal() {
    const $modal = $('.add-product-modal');

    // 点击添加卡片
    $('#products-container').on('click', '.add-card', function () {
        $modal.addClass('active');
        $('body').css('overflow', 'hidden'); // 禁止背景滚动
    });

    // 关闭弹窗
    function closeModal() {
        $modal.removeClass('active');
        $('body').css('overflow', '');
    }

    // 关闭事件
    $modal.on('click', '.btn-close, .btn-outline-primary', closeModal);
    $modal.on('click', function (e) {
        if ($(e.target).hasClass('modal-overlay')) {
            closeModal();
        }
    });

    // ESC关闭
    $(document).on('keyup', function (e) {
        if (e.key === 'Escape') closeModal();
    });
}

// 表单功能
function initProductForm() {
    const $form = $('#productForm');
    const $uploadArea = $('.upload-area');
    const $fileInput = $('<input type="file" hidden accept="image/*">');

    // 文件上传交互
    $uploadArea.on('click', function () {
        $fileInput.trigger('click');
    });

    $fileInput.on('change', function (e) {
        const file = e.target.files[0];
        if (file) {
            $uploadArea.html(`
                <div class="upload-preview">
                    <img src="${URL.createObjectURL(file)}" 
                        class="preview-image"
                        alt="LOGO预览">
                    <p class="mb-0 text-muted">${file.name}</p>
                </div>
            `);
        }
    });


    // 动态加载分类选项
    $.ajax({
        url: apiConfig.productTypes,
        success: function (types) {
            console.log('产品类型数据');
            console.log(types);
            const select = $('[name="product_type"]');
            console.log('下拉框对象' + select)
            types.forEach(type => {
                select.append(
                    `<option value="${type.id}" data-category="${type.category}">${type.name}</option>`
                );
            });
        }
    });

    // 动态加载用户列表
    $.ajax({
        url: apiConfig.users,
        success: function (users) {
            const select = $('select[name="administrators"]');
            users.forEach(user => {
                select.append(
                    `<option value="${user.id}">${user.username}</option>`
                );
            });
            // 初始化多选
            select.select2({
                placeholder: "选择管理员",
                allowClear: true,
                width: '100%'
            });
        }
    });

    // 实时字数统计
    $('[name="description"]').on('input', function () {
        const count = $(this).val().length;
        $('#charCount').text(count);
        $(this).toggleClass('is-invalid', count > 255);
    });

    // 增强表单验证
    $form.on('submit', async function (e) {
        e.preventDefault();

        // 前端验证
        const formData = new FormData(this);
        const errors = [];

        // 验证产品类型
        if (!formData.get('product_type')) {
            errors.push('请选择产品分类');
        }

        // 验证文件类型和大小
        const file = $fileInput[0].files[0];
        if (file) {
            if (!['image/png', 'image/jpeg', 'image/svg+xml'].includes(file.type)) {
                errors.push('仅支持PNG/JPG/SVG格式');
            }
            if (file.size > 2 * 1024 * 1024) {
                errors.push('文件大小不能超过2MB');
            }
        }

        // 显示错误
        if (errors.length > 0) {
            showToast('error', errors.join('<br>'));
            return;
        }

        // 添加当前用户为管理员
        formData.append('administrators', currentUserId);

        try {
            const response = await $.ajax({
                url: '/products/api/create-product/',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false
            });

            // 处理多对多关系
            if (response.administrators) {
                await Promise.all(
                    response.administrators.map(userId =>
                        $.post(`/api/products/${response.id}/add-admin/`, {user_id: userId})
                    )
                );
            }

            showToast('success', '创建成功');
            setTimeout(() => window.location.reload(), 1500);
        } catch (error) {
            const msg = error.responseJSON?.message || '请求失败';
            showToast('error', msg);
        }
    });


    // 表单提交
    $form.on('submit', async function (e) {
        e.preventDefault();

        const formData = new FormData();
        formData.append('name', $form.find('[name="name"]').val());
        formData.append('description', $form.find('[name="description"]').val());
        if ($fileInput[0].files[0]) {
            formData.append('logo', $fileInput[0].files[0]);
        }

        try {
            const response = await $.ajax({
                url: '/products/api/user-products/',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function () {
                    const xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function (e) {
                        const percent = Math.round((e.loaded / e.total) * 100);
                        $uploadArea.html(`上传中 ${percent}%`);
                    });
                    return xhr;
                }
            });

            showToast('success', response.message);
            setTimeout(() => location.reload(), 1500);
        } catch (error) {
            const msg = error.responseJSON?.message || '请求失败';
            showToast('error', msg);
        }
    });
}


// 初始化页面
$(document).ready(function () {
    initAddProductModal();
    initProductForm();

});

